//
//  AddressList_Vc.swift
//  Pods
//
//  Created by eme on 2017/4/1.
//
//


/*
 owner:cy
 update:2017年04月01日09:58:51
 info: 地址选择列表
 */
import RxSwift
import UtilCore
import EmptyDataView
import RickonCore
import BrandonCore

class AddressList_Vc: Empty_TVc {
    
    /****************************Storyboard UI设置区域****************************/
    @IBOutlet weak var addressList_Tv: UITableView!
    
    
    @IBOutlet weak var manage_Btn: UIButton!
    
    @IBOutlet weak var addAddress_Btn: UIButton!
    /*----------------------------   自定义属性区域    ----------------------------*/
    var addid:String?
    var manageVm:AddressList_Vm?
    var addressModelList = [AddressModel]() {
        didSet {
            self.addressList_Tv.reloadData()
        }
    }
    var addressModel:AddressModel?
    var didSelectedAddressModel:((_ addressModel:AddressModel?) -> Void)?
    /****************************Storyboard 绑定方法区域****************************/
    
    
    
    /**************************** 以下是方法区域 ****************************/
    override func viewDidLoad() {
        super.viewDidLoad()
        
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        
    }
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        
    }
    /**
     界面基础设置
     */
    override func setupUI() {
        /**
         *  自定义 导航栏左侧 返回按钮
         */
        self.customLeftBarButtonItem()
        self.tabBarController?.tabBar.isHidden = true
        self.addressList_Tv.tableFooterView = UIView()
        self.addressList_Tv.dzn_tv_emptyDataSource = self
        self.addressList_Tv.dzn_tv_emptyDelegate = self
        ///隐藏滑动条
        self.addressList_Tv.showsVerticalScrollIndicator = false
//        self.addressList_Tv.estimatedRowHeight = 100  //  随便设个不那么离谱的值
//        self.addressList_Tv.rowHeight = UITableViewAutomaticDimension
    }
    /**
     app 主题 设置
     */
    override func setViewTheme(){
        self.addAddress_Btn.changeBorderColor(Theme.btn.normal, cornerRadius: 6.0)
    }
    /**
     绑定到viewmodel 设置
     */
    override func bindToViewModel(){
        self.manageVm = AddressList_Vm(refreshTriger: rx.sentMessage(#selector(AddressList_Vc.viewWillAppear)).map { _ in () }.filter{ _ -> Bool in
            if case  .audited = AppData.appState{
                return true
            }else{
                AuditInfoView.showByView(supView: self.view)
                return false
            }
        })
        self.manageVm?
            .addressListModel
            .subscribe(onNext: { [unowned self] ( listModel ) in
                /// 需要显示空列表
                self.showEmptyView = true
                self.addressModelList = listModel
            })
            .disposed(by: disposeBag)
//        self.manageVm?
//            .loading
//            .asObservable()
//            .bindTo(self.view.rx_loading)
//            .disposed(by: disposeBag)
        
        self.manageVm?
            .error
            .bindTo(self.view.rx_error)
            .disposed(by: disposeBag)
        
        self.addAddress_Btn
            .rx.tap
            .subscribe(onNext: {( _ ) in
               _ = "addnewaddress".openURL()
            })
            .disposed(by: disposeBag)
        self.manage_Btn
            .rx.tap
            .subscribe(onNext: { ( _ ) in
               _ = "magagenewaddress".openURL()
            })
            .disposed(by: disposeBag)
    }
    /**
     自定义返回上级界面
     */
    override func backToView()  {
        ///当点击返回的时候需要判断下数据知否为空
        /*
         1.先判断addressModel是否为空
         */
        if let addressModel = self.addressModel{
            if self.addressModelList.count > 0 {
                var isHas = false
                for item in self.addressModelList{
                    if item.addid == addressModel.addid {
                        isHas = true
                        break
                    }
                }
                if isHas {
                    self.didSelectedAddressModel?(addressModel)
                }else{
                    ///说明已经删除了传过来的model 需要取第一个
                    self.didSelectedAddressModel?(self.addressModelList[0])
                }
            }else{
                ///已经删除为空了所以需要置为nil
                self.didSelectedAddressModel?(nil)
            }
        }
       _ = self.navigationController?.popViewController(animated: true)
    }
}
// MARK: UITableViewDelegate
extension AddressList_Vc :UITableViewDataSource{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
        return  self.addressModelList.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
        let cell = tableView.dequeueReusableCell(withIdentifier: "AddressList_TCell", for: indexPath) as! AddressList_TCell
        let item = self.addressModelList[indexPath.row]
        cell.item = item
        if let addid = self.addid,  addid == item.addid  {
            
            cell.state_ImgV.image = UIImage(named: "paystate-selected", in: AryaCore.bundle, compatibleWith: nil)
        }else{
            cell.state_ImgV.image = UIImage(named: "paystate-unselected", in: AryaCore.bundle, compatibleWith: nil)
        }
        return cell
    }
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
}
// MARK: UITableViewDelegate
extension AddressList_Vc: UITableViewDelegate {
    /// 点击行事件
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath){
        tableView.deselectRow(at: indexPath, animated: true)
        if let didSelectedAddressModel = self.didSelectedAddressModel {
            let item = self.addressModelList[indexPath.row]
            self.addid = item.addid
            didSelectedAddressModel(item )
           _ = self.navigationController?.popViewController(animated: true)
        }
    }
    
}
///EmptyDelegate 空数据代理
extension AddressList_Vc{
    override func didTap(emptyView scrollView: UIScrollView, button: UIButton){
        
    }
}
/// 空数据数据代理
extension AddressList_Vc :EmptyDataSource{
    
    func description(emptyView scrollView: UIScrollView) -> NSAttributedString?{
        return Theme.getEmptyDesc("你还没有收货地址～添加一个吧！")
    }
    func image(emptyView scrollView: UIScrollView) -> UIImage?{
        return UIImage(named: "emptylist-address", in: AryaCore.bundle, compatibleWith: nil)
    }
    func backgroundColor(emptyView scrollView: UIScrollView) -> UIColor?{
        return UIColor.white
    }
}

